<template>
  <div>
    <div v-if="isLoading" class="loading-container">
      <!-- 使用 Vant Loading 组件 -->
      <van-loading type="spinner" size="24px" text="加载中..." color="#1e1e1e" />
    </div>
    <header class="search-header">
      <nav class="songs">
        <div class="fenl">
          <img src="/images/返回.png" alt="" @click="goBack" />
        </div>
        <!-- 确保 v-model 绑定的 value 已在 setup 中定义 -->
        <van-search class="guanjian" v-model="value" placeholder="请输入搜索关键词"  @click="navigateToSearch"/>
        <div class="liaot">
          <img src="/images/聊天.png" alt="" />
        </div>
      </nav>
    </header>

    <div class="fenglei">
      <div class="les">
        <van-sidebar v-model="active">
          <van-sidebar-item v-for="(item, index) in items" :key="index" :title="item.title"
            @click="() => ejlist(index)" />
        </van-sidebar>
      </div>
      <div class="dianjx">
        <div v-for="(item, index) in djitem" :key="index" class="djitem" @click="doSearchWithHistory(item.title)">
          <img :src="item.image" alt="" />
          <div>{{ item.title }}</div>
        </div>
        <div class="erjidj">
          <div class="setsort">
            <button @click="setSort('pop')">综合</button>
            <button @click="setSort('sell')">销量</button>
            <button @click="setSort('new')">新品</button>
          </div>
          <div class="xian"></div>
          <ul class="product-list">
            <!-- 这里通过 v-for 循环展示商品信息，后续会在 Vue 实例中处理 -->
            <li v-for="product in newProducts" :key="product.tradeItemId"  @click="goToItemDetail(product.iid)">
              <van-image width="133rem" height="188rem" fit="cover" :src="product.img" />
              <div class="product-sale">已售{{ product.sale }}件</div>
              <div class="product-title">{{ product.title }}</div>

              <div class="biaoqian">
                <div class="product-price">￥{{ product.price }}</div>
                <!-- <div class="product-iid">{{ product.iid }}</div> -->
                <div class="product-cfav">{{ product.cfav }}<img src="../../public/images/收藏.png" alt="" class="sc">
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getzfenglei } from "@/api/index";
import axios from "axios";

// 使用 Vue Router
const router = useRouter();
const isLoading = ref(true)
// 定义响应式变量
const value = ref(""); // 修复：定义用于 v-model 的 value
const active = ref<number>(0);
const items = ref<Array<{ title: string; maitKey: string }>>([]);
const djitem = ref<Array<{ image: string; title: string; id: number }>>([]);

// 用于存储新获取的商品数据
const newProducts = ref<Array<{ img: string; title: string; price: number; iid: string; cfav: number; sale: number; }>>([]);
// 用于存储当前选中的排序类型，初始化为 'new'（可根据需求调整初始值）
const currentSortType = ref<string>('new');

// 设置排序类型的方法，用于响应按钮点击事件
const setSort = (sortType: string) => {
  currentSortType.value = sortType;
  fetchNewProducts(); // 每次切换排序类型后重新获取商品数据
};

// 获取新商品数据的方法，整合了 API 请求及数据处理逻辑
const fetchNewProducts = async () => {
  const miniWallkey = items.value[active.value].miniWallkey; // 获取当前选中的miniWallkey，假设基于active值来确定当前分类

  const apiUrl = `https://apis.netstart.cn/mogujie/category/miniWall?fcid=${miniWallkey}&sort=${currentSortType.value}`;
  try {
    const response = await axios.get(apiUrl);
    const data = response.data;
    if (data.status.code === 1001 && data.result) {
      const docs = data.result.wall.docs;
      newProducts.value = docs.map((doc: any) => ({
        img: doc.img,
        title: doc.title,
        price: doc.price,
        iid: doc.iid,
        cfav: doc.cfav,
        sale: doc.sale
      }));
    }
  } catch (error) {
    console.error("获取新商品数据失败:", error);
  }
};

// 页面加载时获取分类数据
onMounted(async () => {
  // 保持 isLoading 为 true，直到数据完全加载
  isLoading.value = true;

  try {
    const response = await getzfenglei();
    items.value = response.data.data["117330"].list;
    // 模拟异步数据加载过程
    setTimeout(() => {
      isLoading.value = false; // 数据加载完成后，设置为 false
    }, 1000);  // 假设数据加载有延迟，可以根据实际情况调整
  } catch (error) {
    isLoading.value = false;
    console.error("请求失败:", error);
  }

  if (items.value.length > 0) {
    await ejlist(0);
  }
});


// 获取二级分类数据
const ejlist = async (index: number) => {
  const miniWallkey = items.value[index].miniWallkey;
  const maitKey = items.value[index].maitKey;
  console.log("选中项 maitKey:", maitKey);
  console.log("选中项 miniWallkey:", miniWallkey);

  try {
    const response = await axios.get(
      "https://apis.netstart.cn/mogujie/category/getSub",
      { params: { pid: maitKey } }
      
    );
    djitem.value = response.data.data.list.map((item: any) => ({
      image: item.image,
      title: item.title,
      id: item.id,
      
    }));
    console.log("子分类数据:", djitem.value);

  } catch (error) {
    console.error("获取子分类失败:", error);
  }
  fetchNewProducts();
};
const navigateToSearch = () => {
  router.push('/shop')
}

const goToItemDetail = (iid: string) => {
  router.push({ name: 'TiaoZhuan', params: { iid : iid } });
  console.log("商品详情页的iid:", iid);
};

// 返回上一页的方法
const goBack = () => {
  router.back(); // 使用 Vue Router 的 back 方法返回上一页
};

const doSearchWithHistory = (searchTerm: string) => {
  router.push({
    name: "SearchResult",
    query: {
      q: searchTerm
    }
  });
};
</script>

<style lang="less" scoped>
.fenglei {
  font-size: 12rem;
  display: flex;
  justify-content: space-between;
  margin-top: 43rem;

  .les {
    background-color: #fff;
    position: fixed;
    left: 0;
    z-index: 1000;
    overflow-y: auto;
    height: 100%;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .djitem div.price {
    color: #ff0000; // 假设价格字体颜色为红色，可按需修改
    font-size: 10rem;
  }

  .dianjx {
    width: 300rem;
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
    margin: 20rem 0rem 0 89rem;

    .djitem {
      width: 90rem;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      margin: 10rem 0;

      img {
        width: 65rem;
      }

      div {
        width: 70rem;
        text-align: center;
        font-size: 12rem;
        margin-top: 10rem;
        color: #666666;
      }
    }
  }

  .erjidj {
    width: 100%;
    height: 700rem;
    // background-color: #e4bbbb;
  }
}

.search-header {
  background-color: #fff;
  border-bottom: 1rem solid #e5e5e5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  width: 100%;
}

.songs {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding: 10rem;
  position: static;
}

.fenl {
  width: 10rem;
  display: flex;
  align-items: center;

  img {
    width: 20rem;
  }
}

.liaot {
  img {
    width: 20rem;
  }
}

.guanjian {
  color: #eeeeee;
  width: 83%;
  height: 21rem;
}

.van-sidebar {
  width: 90rem;
}

.van-badge__wrapper {
  margin: 0 auto;
}

.van-sidebar-item {
  padding: 0;
  height: 45rem;
  line-height: 45rem;
  text-align: center;
  color: #666666;
}

.van-sidebar-item--select {
  color: #ff5777;
  font-weight: 600;
}

.van-sidebar-item--select:before {
  background-color: #ff5777;
}

.erjidj {
  width: 100%;

  .setsort {
    width: 100%;
    height: 30rem;
    display: flex;
    // 平均分配宽度
    justify-content: space-around;
    // border-bottom: #e5e5e5 1rem solid;
    border-top: #e5e5e5 1rem solid;

    button {
      width: 33%;
      height: 20rem;
      font-size: 12rem;
      background-color: #fff;
      border: none;
      border-left: 1rem solid #e5e5e5;
      margin-top: 9rem;

    }

    button.hover{
      color: #ff5777 !important;
    }
  }

  .xian {
    width: 100%;
    height: 1rem;
    background-color: #e5e5e5;
  }

  .product-list {
    list-style: none;
    padding: 0;
    margin-top: 5rem;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;

    li {
      display: flex;
      flex-direction: column;
      margin-bottom: 20rem;
      width: 133rem;
      margin-left: 3rem;
      margin-right: 3rem;


      .van-image__img {}

      .product-title {
        font-size: 12rem;
        color: #333;
        text-align: left;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        text-overflow: ellipsis;
        overflow: hidden;
        line-height: 20rem;
        margin: 3rem 3rem;
      }

      .biaoqian {
        display: flex;
        justify-content: space-between;
        margin-top: -5rem;

        .product-price {
          font-size: 15rem;
          margin: 0;
          float: left;
          font-weight: 700;
          color: #ff5777;
          margin-left: 3rem;
        }


        .product-cfav {
          font-size: 12rem;
          color: #999;
          margin-top: 4rem;
          margin-right: 3rem;

          .sc {
            width: 15rem;
            height: 15rem;
            float: right;
            margin-top: -2rem;
            margin-right: 0rem;
          }

        }
      }
    }
  }
}
.product-sale{
          position: absolute;
          width: 55rem;
          text-align: center;
          line-height: 20rem;
          font-size: 10rem;
          height: 20rem;
          margin-top: 150rem;
          color: white;
          // 背景渐变色，从左到右，有黑色到透明
          background-image: linear-gradient(to right, rgb(85, 85, 85), transparent);
        }
        .loading-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);  /* 背景透明效果 */
  z-index: 9999;
}
</style>
